<template>
  <div class="personal-analysis">
    <header>
      <p class="title">学生成绩分析系统</p>
    </header>
    <main>
      <div class="search-bar">
        <div class="item">
          <span class="name">班级：</span>
          <el-select v-model="classValue" placeholder="请选择" clearable @change="onChangeClass">
            <el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="item">
          <span class="name">课程：</span>
          <el-select v-model="courseValue" placeholder="请选择" clearable @change="onChangeCourse">
            <el-option v-for="item in courseOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="item">
          <span class="name">活动：</span>
          <el-select
            v-model="activityValue"
            placeholder="请选择"
            multiple
            collapse-tags
            collapse-tags-tooltip
            clearable
            @change="onChangeActivity"
          >
            <el-option v-for="item in activityOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="main">
        <div class="left-side">
          <Card title="小组活动度">
            <div class="echart" ref="groupLivenessEchartDom"></div>
          </Card>
          <Card title="小组活动度增减比">
            <div class="group-liveness-ratio">
              <div class="list">
                <div class="item" v-for="(item, index) in groupLivenessRatioList" :key="index">
                  <img class="avatar" :src="item.avatar" alt="" />
                  <div class="user-info">
                    <p class="name">{{ item.name }}</p>
                    <p class="value">{{ item.value }}</p>
                    <img v-show="item.value >= 0" class="icon" src="../assets/images/增长.png" alt="" />
                    <img v-show="item.value < 0" class="icon" src="../assets/images/递减.png" alt="" />
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </div>
        <div class="middle-side">
          <div class="top-container">
            <Card title="个人得分">
              <div class="echart" ref="personnalScoreEchartDom"></div>
            </Card>
          </div>
          <div class="bottom-container">
            <Card title="当前开展的活动总数">
              <div class="num">{{ activityTotal }}</div>
            </Card>
            <Card title="所有小组的平均积分">
              <div class="num">{{ averageScore }}</div>
            </Card>
            <Card title="参与学生总人数">
              <div class="num">{{ studentTotal }}</div>
            </Card>
          </div>
        </div>
        <div class="right-side">
          <Card title="个人活跃度">
            <div class="personnal-liveness">
              <div class="list">
                <div class="item" v-for="(item, index) in personnalLivenessList" :key="index" @click="toUserInfo(item)">
                  <img v-if="index === 0" class="icon" src="../assets/images/第一名.png" alt="" />
                  <img v-else-if="index === 1" class="icon" src="../assets/images/第二名.png" alt="" />
                  <img v-else-if="index === 2" class="icon" src="../assets/images/第三名.png" alt="" />
                  <span v-else class="icon">{{ index + 1 }}</span>
                  <div class="user-info">
                    <img class="avatar" :src="item.avatar" alt="" />
                    <p class="name">{{ item.name }}</p>
                  </div>
                  <div class="progress">
                    <div class="bar" :style="{ width: item.width + 'px' }"></div>
                    <div class="name">{{ item.value }}次</div>
                  </div>
                </div>
              </div>
            </div>
          </Card>
          <Card title="小组得分">
            <div class="echart" ref="groupScoreEchartDom"></div>
          </Card>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="js">
import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
import * as echarts from 'echarts'
import Card from '../components/card.vue'

import { reqAllClass, reqAllScore, reqAllActivity, reqGroupLiveness, reqStudentLiveness, reqStudentScore, reqGroupLivenessRatio, reqGroupScore, reqActCount } from '../api/achievementAnalysis'

import COLORS from '../utils/colors.js' 

import AVATARS from '../utils/avatar.js' 

const axisLineStyle = {
  lineStyle: {
    color: '#fff',
  },
}

const legendTextStyle = {
  color: '#fff',
}

const timer = ref(null)

// 获取随机颜色
const generateRandomColors = (count) => {
  const colors = []
  for (let i = 0; i < count; i++) {
    const r = Math.floor(Math.random() * 256)
    const g = Math.floor(Math.random() * 256)
    const b = Math.floor(Math.random() * 256)
    colors.push(`rgb(${r},${g},${b})`)
  }
  return colors
}

// 活动列表
const activityValue = ref([])
const activityOptions = ref([])
const getAllActivityList = () => {
  activityValue.value = []
  if (!courseValue.value || !classValue.value) {
    return
  }
  const params = {
    courseId: courseValue.value,
    jclassId: classValue.value,
  }
  reqAllActivity(params).then((res) => {
    if (res.code != 200) return
    const list = res.data.map((i) => { return  {
      label: i.name,
      value: i.id
    }})
    activityOptions.value = list
  })
}
const onChangeActivity = () => {
  clearInterval(timer.value)
  updatePage()
  setIntervalFn()
}

// 班级列表
const classOptions = ref([])
const classValue = ref('')
const getAllClassList = () => {
  reqAllClass().then((res) => {
    if (res.code != 200) return
    const list = Object.keys(res.data).map((i) => { return  {
      label: i,
      value: res.data[i]
    }})
    for (let i = 0; i < list.length; i++) {
  if (list[i].label === "大数据高二3班（3+2）") {
    list[i].label = "大数据高二年级5班"; // 这里将班级名称更改为你需要的值
  }
}
    classOptions.value = list
    console.log(list);
  })
}
const onChangeClass = () => {
  activityValue.value = []
  activityOptions.value = []
  getAllActivityList()
}

// 课程列表
const courseValue = ref('')
const courseOptions = ref([])
const getAllScoreList = () => {
  reqAllScore().then((res) => {
    if (res.code != 200) return
    const list = Object.keys(res.data).map((i) => { return  {
      label: i,
      value: res.data[i]
    }})
    courseOptions.value = list
  })
}
const onChangeCourse = () => {
  activityValue.value = []
  activityOptions.value = []
  getAllActivityList()
}

// 小组活跃度
const groupLivenessEchartDom = ref(null)
let groupLivenessEchart = null
// 更新小组活跃度echart
const updategroupLivenessEchart = (lengendData, radarIndicatorData, seriesData) => {
  let option = {
    tooltip: {
      trigger: 'item',
    },
    // legend: {
    //   bottom: '5%',
    //   left: '5%',
    //   textStyle: legendTextStyle,
    //   data: lengendData,
    // },
    radar: {
      // shape: 'circle',
      indicator: radarIndicatorData,
      center: ['50%', '50%'],
      radius: ['0%', '60%'],
    },
    series: [
      {
        type: 'radar',
        data: seriesData,
      },
    ],
  }
  if (radarIndicatorData.length && seriesData.length) {
    groupLivenessEchart && groupLivenessEchart.setOption(option)
  } else {
    groupLivenessEchart && groupLivenessEchart.clear()
  }
}
const getGroupLiveness = () => {
  const params = {
    activeIdList: activityValue.value,
    classId: classValue.value,
  }
  reqGroupLiveness(params).then((res) => {
      const radarIndicatorData = []
      const seriesData = []
      let lengendData = []

      if(res.data.length) {
        const liveness = []
        const totalScore = []

        res.data.forEach((i) => {
          liveness.push(i.liveness)
          totalScore.push(i.totalScore)
          radarIndicatorData.push({
            name: i.groupName,
            // max: Math.max(...liveness, ...totalScore) || 1
          })
        })

        lengendData = ['活跃度', '总分数']

        seriesData.push({
          name: '活跃度',
          value: liveness
        })

        seriesData.push({
          name: '总分数',
          value: totalScore
        })

      }
      updategroupLivenessEchart(lengendData, radarIndicatorData, seriesData)
  })
}

// 小组活动度递增比
const groupLivenessRatioList = ref([])
const getgroupLivenessRatioList = () => {
  groupLivenessRatioList.value = []
  const params = {
    activeIdList: activityValue.value,
    classId: classValue.value,
  }
  reqGroupLivenessRatio(params).then((res) => {
    res.data.forEach((item, index) => {
      groupLivenessRatioList.value.push({
        name: item.groupName,
        value: item.livenessRatio,
        avatar: item.imageUrl || AVATARS[index]
      })
    })
  }).catch((err) => {})
}

// 个人活跃度
let personnalLivenessList = ref([])
const getPersonnalLiveness = () => {
  const params = {
    "courseId": courseValue.value,
    "classId": classValue.value
  }
  reqStudentLiveness(params).then((res) => {
    personnalLivenessList.value = []
    const sum = res.data.map((i)=> i.liveness).reduce((accumulator, currentValue) => accumulator + currentValue, 0);
    res.data.forEach((item, index) => {
      const newItem = {
        name: item.studentName,
        value: item.liveness,
        width: ((Number(item.liveness) / sum)*100).toFixed(2)*1,
        avatar: AVATARS[index] || AVATARS[index % AVATARS.length],
      }
      personnalLivenessList.value.push(newItem)
    })
  }).catch((err) => {})
}

// 小组得分
const groupScoreEchartDom = ref(null)
let groupScoreEchart = null
// 更新小组得分echart
const updateGroupScoreEchart = (seriesData) => {
  let option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      bottom: '5%',
      left: 'center',
      textStyle: legendTextStyle,
    },
    series: [
      {
        type: 'pie',
        top: '0%',
        bottom: '10%',
        radius: ['40%', '60%'],
        label: {
          color: '#ffffff',
          position: 'outside',
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold',
          },
        },
        data: seriesData,
      },
    ],
  }
  if (seriesData.length) {
    groupScoreEchart && groupScoreEchart.setOption(option)
  } else {
    groupScoreEchart && groupScoreEchart.clear()
  }
}
const getGroupScore = () => {
  const params = {
    activeIdList: activityValue.value,
    classId: classValue.value,
  }
  reqGroupScore(params).then((res) => {
    const seriesData = []
    res.data.forEach((item) => {
      seriesData.push({
        name: item.groupname,
        value: item.score,
      })
    })
    updateGroupScoreEchart(seriesData)
  }).catch((err) => {})
}

// 个人得分
const personnalScoreEchartDom = ref(null)
let personnalScoreEchart = null
// 更新个人得分echart
const updatePersonnalScoreEchart = (yAxisData, seriesData) => {
  let option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '6%',
      bottom: '3%',
      top: '1%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      axisLine: axisLineStyle,
      splitLine: {
        show: false,
      },
    },
    yAxis: {
      // type: 'category',
      data: yAxisData,
      axisLine: axisLineStyle,
      axisLabel: {
        show: true,
      },
    },
    series: [
      {
        type: 'bar',
        // barWidth: 28,
        data: seriesData,
      },
    ],
  }
  if (seriesData.length) {
    personnalScoreEchart && personnalScoreEchart.setOption(option)
  } else {
    personnalScoreEchart && personnalScoreEchart.clear()
  }
}
const getPersonnalScore = () => {
  const params = {
    activeIdList: activityValue.value,
    classId: classValue.value,
  }

  reqStudentScore(params).then((res) => {
    // const colors = generateRandomColors(res.data.length + 1)
    const colors = COLORS

    const seriesData = []
    const yAxisData = []
    res.data.forEach((item, index) => {
      yAxisData.push(item.name)

      const newItem = {
        value: item.score,
        itemStyle: {
          color: colors[index],
        },
      }
      seriesData.push(newItem)
    })

    updatePersonnalScoreEchart(yAxisData, seriesData)
  }).catch((err) => {})

}

// 当前开展的活动总数
const activityTotal = ref(0)

// 所有小组的平均积分
const averageScore = ref(0)

// 参与学生总人数
const studentTotal = ref(0)

const getAllCount = () => {
  const params = {
    courseId: courseValue.value,
    classId: classValue.value,
  }
  reqActCount(params).then((res) => {
    activityTotal.value = res.data.actNum
    averageScore.value = res.data.actNum ? res.data.groupAvg.toFixed(2) : 0
    // studentTotal.value = res.data.studentNum
    studentTotal.value = 30
  }).catch((err) => {})
}

const onResize = () => {
  groupLivenessEchart.resize()
  groupScoreEchart.resize()
  personnalScoreEchart.resize()
}

// 初始化Echarts
const initEcharts = () => {
  // 小组活跃度
  groupLivenessEchart = echarts.init(groupLivenessEchartDom.value)
  // getGroupLiveness()

  // 小组得分
  groupScoreEchart = echarts.init(groupScoreEchartDom.value)
  // getGroupScore()

  // 个人得分
  personnalScoreEchart = echarts.init(personnalScoreEchartDom.value)
  // getPersonnalScore()
}

const toUserInfo = (item) => {
  // const names = ['牟孝杨', '谭春勇']
  // if (names.includes(item.name)) {
    router.push({ path: '/PersonalAnalysis', query: { courseId: courseValue.value, name: item.name } })
  // }
}

const updatePage = () => {
  getGroupLiveness()
  getPersonnalScore()
  getPersonnalLiveness()
  getgroupLivenessRatioList()
  getGroupScore()
  getAllCount()
}

const setIntervalFn = () => {
  timer.value = setInterval(() => {
    if (activityValue.value.length) {
      console.log('有活动，开始走');
      updatePage()
    } else {
      console.log('没有活动 清除');
      return clearInterval(timer.value)
    }
  }, 10000);
}

onMounted(() => {
  document.title = '学生成绩分析系统'
  getAllClassList()
  getAllScoreList()
  // getAllActivityList()
  initEcharts()
  // getPersonnalLiveness()
  // getgroupLivenessRatioList()
  // getActivityTotal()
  // getAverageScore()
  // getStudentTotal()
  nextTick(() => {
    window.addEventListener('resize', onResize)
    // setIntervalFn()
  })
})

onActivated(() => {
  console.log('onActivated');
  setIntervalFn()
})

onDeactivated(() => {
  console.log('onDeactivated ');
  activityValue.value = []
  clearInterval(timer.value)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', onResize)
  clearInterval(timer.value)
})
</script>

<style lang="scss" scoped>
.personal-analysis {
  width: 100%;
  height: 100%;
  color: #fff;
}
header {
  width: 100%;
  height: 72px;
  background-color: rgb(0, 21, 41);
  .title {
    padding-left: 16px;
    line-height: 72px;
    font-size: 36px;
    color: #fff;
    font-weight: 700;
  }
}
main {
  width: 100%;
  height: calc(100% - 72px);
}
.search-bar {
  padding: 16px 16px 8px 16px;
  display: flex;
  width: 100%;
  .item {
    display: flex;
    align-items: center;
    margin-right: 32px;

    .name {
      display: inline-block;
      width: 60px;
      color: #000000;
    }
    .el-select {
      width: 200px;
    }
  }
}
.main {
  display: flex;
  padding: 0 16px 16px 16px;
  width: 100%;
  height: calc(100% - 56px);
  .left-side {
    flex: 1;
    height: 100%;
    .card {
      height: 50%;
    }
    .card:first-child {
      padding-bottom: 8px;
    }
    .card:last-child {
      padding-top: 8px;
    }
  }
  .middle-side {
    padding: 0 16px;
    flex: 2;
    height: 100%;
    .top-container {
      padding-bottom: 8px;
      width: 100%;
      height: 75%;
    }
    // .top-container > .card {
    //   height: 100%;
    // }
    .bottom-container {
      padding-top: 8px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      height: 25%;
    }
    .bottom-container > .card {
      width: calc((100% - 32px) / 3);
      // flex: 1;
      height: 100%;
    }
    .bottom-container .num {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 40px;
    }
  }
  .right-side {
    flex: 1;
    height: 100%;
    .card {
      width: 100%;
      height: 50%;
    }
    .card:first-child {
      padding-bottom: 8px;
    }
    .card:last-child {
      padding-top: 8px;
    }
  }
  .echart {
    width: 100%;
    height: 100%;
  }
  // 个人活跃度
  .personnal-liveness {
    width: 100%;
    height: 100%;
    .list {
      width: 100%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: auto;
    }
    .item {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      padding: 0 16px;
      width: 100%;
      .icon {
        text-align: center;
        line-height: 32px;
        width: 32px;
        height: 32px;
        margin-right: 10px;
      }
      .user-info {
        display: flex;
        align-items: center;
        width: 100px;
        cursor: pointer;
      }
      .user-info .avatar {
        width: 32px;
        height: 32px;
        border-radius: 4px;
        margin-right: 10px;
      }
      .user-info .name {
        width: calc(100% - 28px);
      }
      .progress {
        display: flex;
        width: calc(100% - 42px - 100px);
      }
      .progress .bar {
        margin-right: 8px;
        height: 20px;
        background-color: #60a3fc;
      }
      .progress .name {
      }
    }
  }
  // 小组活动度增减比
  .group-liveness-ratio {
    width: 100%;
    height: 100%;
    .list {
      padding: 16px;
      display: grid;
      align-items: center;
      grid-template-columns: 1fr 1fr; // 列按1:2:1自动分配
      grid-template-rows: 1fr 1fr; // 行按1:2自动分配
      gap: 16px 16px; // 第一个参数为不同行之间的间距, 第二个为不同列之间的间距
      width: 100%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: auto;
    }
    .item:nth-child(even) {
      justify-self: start;

    }
    .item:nth-child(odd) {
      justify-self: end;
    }
    .item {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      margin: 8px;
      padding: 16px;
      width: 120px;
      height: 120px;
      border-radius: 10px;
      background-color: #1e2932;
      .avatar {
        width: 60px;
        height: 60px;
        border-radius: 10px;
      }
      .user-info {
        width: 100%;
        display: flex;
        justify-content: space-around;
      }
    }
  }
}
</style>
